package com.embracesource.plugin.notes;

import com.embracesource.plugin.common.CompanyInfo;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AddNotes extends AnAction {

    private static final Pattern PATTERN = Pattern.compile("(\\n@\\S|public class)+");
    private static final String FILE_TYPE_JAVA = "JAVA";
    private static final String NOTES_TEMPLATE = "\n" +
            "/** \n" +
            " * <p> \n" +
            " * \n" +
            " * @Description: [%s] \n" +
            " * @Author: [%s] \n" +
            " * @CreateDate: [%s] \n" +
            " * </p> \n" +
            " * \n" +
            " */";

    @Override
    public void actionPerformed(AnActionEvent event) {
        PropertiesComponent instance = PropertiesComponent.getInstance();
        String author = instance.getValue("embracesource.notes.author");
        final FileEditor data = event.getData(PlatformDataKeys.FILE_EDITOR);
        VirtualFile file = data.getFile();
        String fileType = file.getFileType().getName();
        if (FILE_TYPE_JAVA.equals(fileType)) {
            final Editor editor = event.getRequiredData(CommonDataKeys.EDITOR);
            final Project project = event.getRequiredData(CommonDataKeys.PROJECT);
            final Document document = editor.getDocument();
            String classDescribe = Messages.showInputDialog(CompanyInfo.NAME, "Class Notes", Messages.getQuestionIcon());
            LocalDate today = LocalDate.now();
            DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            String format = today.format(formatters);
            String describe = String.format(NOTES_TEMPLATE, classDescribe, author, format);
            Matcher matcher = PATTERN.matcher(document.getText());
            if (matcher.find()) {
                int start = matcher.start();
                WriteCommandAction.runWriteCommandAction(project, () ->
                        document.insertString(start, describe)
                );
            }
        }
    }
}
